package com.lhy.security.core;

import com.lhy.security.annotation.GPermission;
import com.lhy.security.config.GSecurityConst;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

/**
 * 配置权限管理组件使用
 */
public class SInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在调用Controller方法前检查权限信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 方法级拦截器
        if (!(handler instanceof HandlerMethod))
            return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 如果没有被注解声明需要权限则不拦截
        if (! handlerMethod.hasMethodAnnotation(GPermission.class))
            return true;
        // 未登录时拦截，并返回提示信息
        if (! GSecurity.isLogin()){
            response.getWriter().println(GSecurityConst.NO_PERMISSION);
            return false;
        }
        // 检查权限
        GPermission requirePermission = handlerMethod.getMethodAnnotation(GPermission.class);
        HashSet<String> permissions = GSecurity.getPermission();
        if (permissions == null)
            return false;
        if (! permissions.contains(requirePermission.value())){
            response.getWriter().println(GSecurityConst.NO_PERMISSION);
            return false;
        }
        return true;
    }
}
